package com.jasonchoi.security.commons.security.authentication;

import cn.hutool.core.util.StrUtil;
import com.jasonchoi.security.commons.base.BaseRestResult;
import com.jasonchoi.security.commons.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: JasonChoi
 * @Date: 2020/1/8 15:57
 */
@Component
public class JWTAuthorizationFilter extends OncePerRequestFilter {

    /**
     * 存放Token的Header Key
     */
    @Value("${global.jwt.header}")
    private String jwtHeader;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String jwtStr = request.getHeader(jwtHeader);
        if (StrUtil.isBlank(jwtStr)) {
            //走登录逻辑
            chain.doFilter(request, response);
            return;
        }
        if (!JwtUtil.validJwt(jwtStr)) {
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.getWriter().write(BaseRestResult.needLogin().setMessage("用户未登录").toJson());
            return;
        }
        String username = JwtUtil.getUsername(jwtStr);
        String userRoles = JwtUtil.getUserRole(jwtStr);
        //用户权限
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if (StrUtil.isNotBlank(userRoles)) {
            String[] roles = userRoles.split(",");
            authorities = Arrays.asList(roles).stream().filter(StrUtil::isNotBlank)
                                .map(role -> new SimpleGrantedAuthority(role.trim()))
                                .collect(Collectors.toList());
        }
        User user = new User(username, "", authorities);
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user, null, authorities));
        chain.doFilter(request, response);
    }
}
